<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\common\model\ServiceOrder;
use think\Db;

class AutoCompleteServiceOrder extends Command
{
    protected function configure()
    {
        $this->setName('order:auto_complete_service')
            ->setDescription('自动完成超时未完成的服务项目订单');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始处理超时未完成的服务项目订单...');
        
        // 查找超过7天已支付但未完成的订单
        $time = time() - (7 * 24 * 3600); // 当前时间减去7天
        $orders = ServiceOrder::where([
            'status' => ServiceOrder::STATUS_PAID,  // 已支付状态
            'pay_time' => ['<', $time]
        ])->select();
            
        if (empty($orders)) {
            $output->writeln('没有需要处理的订单');
            return;
        }
        
        foreach ($orders as $order) {
            Db::startTrans();
            try {
                // 更新订单状态为已完成
                $order->status = ServiceOrder::STATUS_FINISH;
                $order->save();
                
               
                Db::name('user')->where('id', $order->teacher_id)->setInc('money', $order->amount);
                Db::name('user_money_log')->insert([
                    'user_id' => $order->teacher_id,
                    'money' => $order->amount,
                    'before' => Db::name('user')->where('id', $order->teacher_id)->value('money') - $order->amount,
                    'after' => Db::name('user')->where('id', $order->teacher_id)->value('money'),
                    'memo' => '服务单号：'. $order->order_no,
                    'type' => 'service_income',
                    'service_order_id' => $order->id,
                    'createtime' => time()
                ]);
                // 创建系统消息
                \app\common\model\SystemMessage::create([
                    'user_id' => $order->user_id,
                    'type' => 'service',
                    'title' => '订单已完成',
                    'content' => "您的服务项目订单 {$order->order_no} 已自动完成",
                    'order_id' => $order->id,
                    'order_no' => $order->order_no
                ]);
                
                Db::commit();
                $output->writeln("订单 {$order->order_no} 已完成");
            } catch (\Exception $e) {
                Db::rollback();
                $output->writeln("订单 {$order->order_no} 完成失败：" . $e->getMessage());
            }
        }
        
        $output->writeln('处理完成');
    }
}